package io;

import java.io.*;

public class DataStreamDemo {
    public static void main(String[] args) {
        String dataFile = "data.dat";

        // 写入基本数据类型
        try (DataOutputStream dos = new DataOutputStream(
                new FileOutputStream(dataFile))) {

            dos.writeInt(100);          // 写入int
            dos.writeDouble(3.14159);   // 写入double
            dos.writeBoolean(true);     // 写入boolean
            dos.writeUTF("Hello World"); // 写入UTF-8字符串

            System.out.println("数据写入完成");

        } catch (IOException e) {
            e.printStackTrace();
        }

        // 读取基本数据类型（必须按写入顺序读取）
        try (DataInputStream dis = new DataInputStream(
                new FileInputStream(dataFile))) {

            int num = dis.readInt();
            double pi = dis.readDouble();
            boolean flag = dis.readBoolean();
            String str = dis.readUTF();

            System.out.println("读取的数据：");
            System.out.println("int: " + num);
            System.out.println("double: " + pi);
            System.out.println("boolean: " + flag);
            System.out.println("String: " + str);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
